package com.tanhua.app.interceptor;

import com.tanhua.app.service.UserService;
import com.tanhua.domain.db.User;
import com.tanhua.domain.vo.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override//在controller前拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token  getHeader获取单个请求头Authorization对应的value值
        String token = request.getHeader("Authorization");//请求参数Authorization 令牌=token
        if (token == null) {
            response.setStatus(400);
            return false;

        }

        User user = userService.fromRedisUser(token);
        if(user==null){
            response.setStatus(400); //权限不足
            return false;//中断请求
        }
        // 将用户放在threadLocal中
        UserHolder.saveUser(user);
        // 放行
        return true;
    }


    @Override//响应结束 threadLocal移除对象
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser(); //移除对象
    }
}
